package com.ruoyi.checksystem.service.impl;

import java.util.List;
import java.util.Date;
import java.util.Calendar;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.checksystem.mapper.VipPackageMapper;
import com.ruoyi.checksystem.domain.VipPackage;
import com.ruoyi.checksystem.domain.RechargeRecord;
import com.ruoyi.checksystem.service.IVipPackageService;
import com.ruoyi.checksystem.service.IRechargeRecordService;
import com.ruoyi.checksystem.service.IUserinfoService;
import com.ruoyi.checksystem.domain.Userinfo;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;

/**
 * VIP套餐Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-19
 */
@Service
public class VipPackageServiceImpl implements IVipPackageService {
    private static final Logger log = LoggerFactory.getLogger(VipPackageServiceImpl.class);

    @Autowired
    private VipPackageMapper vipPackageMapper;
    
    @Autowired
    private IRechargeRecordService rechargeRecordService;
    
    @Autowired
    private IUserinfoService userinfoService;

    /**
     * 查询VIP套餐
     *
     * @param id VIP套餐主键
     * @return VIP套餐
     */
    @Override
    public VipPackage selectVipPackageById(Long id) {
        return vipPackageMapper.selectVipPackageById(id);
    }

    /**
     * 查询VIP套餐列表
     *
     * @param vipPackage VIP套餐
     * @return VIP套餐
     */
    @Override
    public List<VipPackage> selectVipPackageList(VipPackage vipPackage) {
        return vipPackageMapper.selectVipPackageList(vipPackage);
    }

    /**
     * 新增VIP套餐
     *
     * @param vipPackage VIP套餐
     * @return 结果
     */
    @Override
    public int insertVipPackage(VipPackage vipPackage) {
        vipPackage.setCreateTime(DateUtils.getNowDate());
        return vipPackageMapper.insertVipPackage(vipPackage);
    }

    /**
     * 修改VIP套餐
     *
     * @param vipPackage VIP套餐
     * @return 结果
     */
    @Override
    public int updateVipPackage(VipPackage vipPackage) {
        vipPackage.setUpdateTime(DateUtils.getNowDate());
        return vipPackageMapper.updateVipPackage(vipPackage);
    }

    /**
     * 批量删除VIP套餐
     *
     * @param ids 需要删除的VIP套餐主键
     * @return 结果
     */
    @Override
    public int deleteVipPackageByIds(Long[] ids) {
        return vipPackageMapper.deleteVipPackageByIds(ids);
    }

    /**
     * 删除VIP套餐信息
     *
     * @param id VIP套餐主键
     * @return 结果
     */
    @Override
    public int deleteVipPackageById(Long id) {
        return vipPackageMapper.deleteVipPackageById(id);
    }

    /**
     * 充值VIP套餐
     * 
     * @param vipPackage 套餐参数
     * @return 结果
     */
    @Override
    @Transactional
    public int rechargeVipPackage(VipPackage vipPackage) {
        if (vipPackage == null || vipPackage.getUserId() == null) {
            log.error("充值参数异常：{}", vipPackage);
            return 0; // 返回失败
        }

        // 如果是查询操作，直接返回查询结果
        Object operationType = vipPackage.getParams().get("operationType");
        if ("query".equals(operationType)) {
            log.info("查询套餐信息: {}", vipPackage.getUserId());
            return 1; // 返回成功，前端会通过其他方法获取结果
        }

        // 保存充值记录前获取用户信息
        Userinfo userinfo = userinfoService.selectUserinfoById(vipPackage.getUserId());
        if (userinfo == null) {
            log.error("用户不存在: {}", vipPackage.getUserId());
            return 0; // 返回失败
        }

        // 检查是否存在充值记录
        boolean hasRechargeHistory = false;
        List<RechargeRecord> history = getUserRechargeHistory(vipPackage.getUserId());
        if (history != null && !history.isEmpty()) {
            hasRechargeHistory = true;
            log.info("用户 {} 有充值记录，记录数量: {}", vipPackage.getUserId(), history.size());
        } else {
            log.info("用户 {} 没有充值记录", vipPackage.getUserId());
        }

        // 获取用户当前最新的套餐类型
        String latestPackageType = null;
        VipPackage existingPackage = selectVipPackageByUserId(vipPackage.getUserId());
        if (existingPackage != null && StringUtils.isNotBlank(existingPackage.getPackageType())) {
            latestPackageType = existingPackage.getPackageType();
            log.info("用户 {} 最新套餐类型: {}", vipPackage.getUserId(), latestPackageType);
        } else {
            log.info("用户 {} 没有现有套餐", vipPackage.getUserId());
        }

        int result = 0;

        // 检查前端是否传递了充值类型标记
        if (vipPackage.getRecordDetails() != null && vipPackage.getRecordDetails() instanceof java.util.Map) {
            java.util.Map<?, ?> recordDetailsMap = (java.util.Map<?, ?>) vipPackage.getRecordDetails();
            
            // 强制检查: 优先检查forcePackageType标记，这是最高优先级
            Object forcePackageTypeObj = recordDetailsMap.get("forcePackageType");
            if (forcePackageTypeObj != null && "无套餐".equals(forcePackageTypeObj.toString())) {
                // 无条件设置为"无套餐"，任何类型的自定义充值都必须是无套餐
                vipPackage.setPackageType("无套餐");
                log.info("【高优先级】根据前端传递的forcePackageType标记，强制设置用户{}的套餐类型为无套餐", vipPackage.getUserId());
            } 
            // 检查retainOriginalPackage标记
            else if (recordDetailsMap.get("retainOriginalPackage") != null && 
                    Boolean.TRUE.equals(recordDetailsMap.get("retainOriginalPackage")) && 
                    existingPackage != null && StringUtils.isNotBlank(existingPackage.getPackageType())) {
                // 保留用户原有套餐类型
                vipPackage.setPackageType(existingPackage.getPackageType());
                log.info("【保留套餐】根据retainOriginalPackage标记，保留用户{}的原套餐类型: {}", 
                         vipPackage.getUserId(), existingPackage.getPackageType());
            }
            // 次优先: 检查rechargeType标记
            else if (recordDetailsMap.get("rechargeType") != null && "normal".equals(recordDetailsMap.get("rechargeType").toString())) {
                // 修改后的逻辑 - 只有当用户没有套餐时，才设置为"无套餐"
                // 如果用户已有套餐，保持原套餐类型不变
                if (existingPackage == null || StringUtils.isBlank(existingPackage.getPackageType()) || 
                    "无套餐".equals(existingPackage.getPackageType())) {
                    vipPackage.setPackageType("无套餐");
                    log.info("【自定义充值】无套餐用户，设置用户{}的套餐类型为无套餐", vipPackage.getUserId());
                } else {
                    // 如果前端没有指定packageType，则保持原套餐类型
                    if (StringUtils.isBlank(vipPackage.getPackageType())) {
                        vipPackage.setPackageType(existingPackage.getPackageType());
                    }
                    log.info("【自定义充值】保留用户{}的原套餐类型: {}", vipPackage.getUserId(), vipPackage.getPackageType());
                }
            } else {
                // 只有在非自定义充值的情况下，才保留用户指定的套餐类型
                log.info("【套餐充值】用户{}使用套餐类型充值: {}", vipPackage.getUserId(), vipPackage.getPackageType());
            }
        } else {
            // 没有详细信息，默认设置为"无套餐"
            vipPackage.setPackageType("无套餐");
            log.info("【无详细信息】默认设置用户{}的套餐类型为无套餐", vipPackage.getUserId());
        }
        
        // 如果存在套餐，判断是否已过期
        if (existingPackage != null) {
            // 更新现有套餐
            log.info("用户{}已有套餐，进行更新", vipPackage.getUserId());
            
            // 计算新的到期时间
            Date endTime = existingPackage.getEndTime();
            // 如果已经过期，则从当前时间开始计算
            if (endTime == null || endTime.before(new Date())) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                // 在当前时间基础上添加天数
                cal.add(Calendar.DAY_OF_MONTH, vipPackage.getExtensionDays() != null ? vipPackage.getExtensionDays() : 30);
                Date newEndTime = cal.getTime();
                vipPackage.setEndTime(newEndTime);
            } else {
                // 如果没过期，则在原到期时间基础上延长
                Calendar cal = Calendar.getInstance();
                cal.setTime(endTime);
                // 在原有结束时间基础上添加天数
                cal.add(Calendar.DAY_OF_MONTH, vipPackage.getExtensionDays() != null ? vipPackage.getExtensionDays() : 30);
                Date newEndTime = cal.getTime();
                vipPackage.setEndTime(newEndTime);
            }
            
            // 更新套餐
            vipPackage.setId(existingPackage.getId());
            // 设置总额度和已使用额度
            // 总额度始终累加，保持历史记录
            int newTotalQuota = (existingPackage.getTotalQuota() != null ? existingPackage.getTotalQuota() : 0) + 
                               (vipPackage.getTotalQuota() != null ? vipPackage.getTotalQuota() : 0);
            log.info("总额度始终累加：原积分: {}，新增积分: {}，总积分: {}", 
                (existingPackage.getTotalQuota() != null ? existingPackage.getTotalQuota() : 0),
                (vipPackage.getTotalQuota() != null ? vipPackage.getTotalQuota() : 0),
                newTotalQuota);
                
            vipPackage.setTotalQuota(newTotalQuota);
            // 设置已使用额度
            if (existingPackage.getUsedQuota() != null) {
                vipPackage.setUsedQuota(existingPackage.getUsedQuota());
            }
            vipPackage.setStartTime(existingPackage.getStartTime());
            vipPackage.setUpdateTime(new Date()); // 更新时间
            
            result = vipPackageMapper.updateVipPackage(vipPackage);
        } else {
            // 创建新套餐
            log.info("用户{}无套餐，创建新套餐", vipPackage.getUserId());
            
            // 设置结束时间
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.DAY_OF_MONTH, vipPackage.getExtensionDays() != null ? vipPackage.getExtensionDays() : 30);
            Date newEndTime = cal.getTime();
            vipPackage.setEndTime(newEndTime);
            
            // 设置套餐开始和结束时间
            vipPackage.setStartTime(new Date());
            // 确保总额度有效
            if (vipPackage.getTotalQuota() == null) {
                vipPackage.setTotalQuota(0);
            }
            // 初始已使用额度设为0
            vipPackage.setUsedQuota(0);
            vipPackage.setCreateTime(new Date());
            vipPackage.setUpdateTime(new Date());
            // 将删除标记设为0(未删除)
            vipPackage.setIsDeleted(0);
            
            result = vipPackageMapper.insertVipPackage(vipPackage);
        }
        
        // 检查是否需要创建充值记录
        if (result > 0) {
            log.info("需要创建充值记录，userId={}, packageType={}, packagePrice={}", 
                     vipPackage.getUserId(), vipPackage.getPackageType(), vipPackage.getPackagePrice());
            
            try {
                // 创建充值记录
                RechargeRecord rechargeRecord = new RechargeRecord();
                rechargeRecord.setUserId(vipPackage.getUserId());
                
                // 查询用户手机号
                String phone = "";
                try {
                    Userinfo user = userinfoService.selectUserinfoById(vipPackage.getUserId());
                    if (user != null && user.getPhone() != null) {
                        phone = user.getPhone();
                    }
                } catch (Exception e) {
                    log.warn("获取用户手机号失败", e);
                }
                rechargeRecord.setPhone(phone);
                
                // 优先使用前端直接传递的packagePrice
                Integer packagePrice = vipPackage.getPackagePrice();
                log.info("直接获取的packagePrice值: {}", packagePrice);
                
                // 如果packagePrice无效，尝试从recordDetails中获取
                if (packagePrice == null || packagePrice <= 0) {
                    log.info("packagePrice无效，尝试直接从recordDetails中获取amount值");
                    
                    // 检查是否有前端传递的支付金额
                    if (vipPackage.getRecordDetails() != null) {
                        log.info("recordDetails不为空: {}", vipPackage.getRecordDetails());
                        try {
                            // 尝试将recordDetails转换为Map来获取amount值
                            if (vipPackage.getRecordDetails() instanceof java.util.Map) {
                                java.util.Map<?, ?> recordDetailsMap = (java.util.Map<?, ?>) vipPackage.getRecordDetails();
                                log.info("recordDetails是Map类型: {}", recordDetailsMap);
                                
                                Object amountObj = recordDetailsMap.get("amount");
                                if (amountObj != null) {
                                    log.info("从Map中获取到amount值: {}", amountObj);
                                    
                                    if (amountObj instanceof Number) {
                                        packagePrice = ((Number) amountObj).intValue();
                                        log.info("将amount转换为Integer: {}", packagePrice);
                                    } else if (amountObj instanceof String) {
                                        try {
                                            packagePrice = Integer.parseInt(amountObj.toString());
                                            log.info("将String类型的amount转换为Integer: {}", packagePrice);
                                        } catch (NumberFormatException e) {
                                            log.warn("无法将String类型的amount [{}] 转换为Integer: {}", amountObj, e.getMessage());
                                        }
                                    } else {
                                        log.warn("amount不是Number或String类型: {}, 类型: {}", amountObj, amountObj.getClass().getName());
                                    }
                                } else {
                                    log.warn("Map中不包含amount键");
                                }
                            } else {
                                log.warn("recordDetails不是Map类型，无法提取amount值: {}", vipPackage.getRecordDetails().getClass().getName());
                            }
                        } catch (Exception e) {
                            log.warn("尝试提取amount时发生异常: {} - 异常详情: {}", e.getMessage(), e);
                        }
                    } else {
                        log.warn("recordDetails为空，无法提取金额");
                    }
                }
                
                // 如果仍然没有有效的金额，使用默认值
                if (packagePrice == null || packagePrice <= 0) {
                    log.warn("packagePrice仍然无效({}), 使用默认金额100元", packagePrice);
                    packagePrice = 100; // 默认价格
                } else {
                    log.info("最终使用的packagePrice: {}", packagePrice);
                }
                
                rechargeRecord.setAmount(packagePrice);
                
                // 构建套餐详情JSON
                String packageDetails;
                
                // 尝试直接从recordDetails中获取packageDetails
                if (vipPackage.getRecordDetails() != null && vipPackage.getRecordDetails() instanceof java.util.Map) {
                    java.util.Map<?, ?> recordDetailsMap = (java.util.Map<?, ?>) vipPackage.getRecordDetails();
                    
                    // 尝试直接获取packageDetails字段
                    Object packageDetailsObj = recordDetailsMap.get("packageDetails");
                    if (packageDetailsObj != null && packageDetailsObj instanceof String) {
                        // 直接使用前端传递的packageDetails
                        packageDetails = (String) packageDetailsObj;
                        log.info("直接使用前端传递的packageDetails: {}", packageDetails);
                    } else {
                        // 手动构建packageDetails
                        packageDetails = String.format(
                            "{\"price\": %d, \"points\": %d, \"duration\": \"%d天\"}", 
                            packagePrice, 
                            // 优先使用单次充值积分，确保显示的是本次充值的积分值
                            vipPackage.getSingleRechargePoints() != null ? vipPackage.getSingleRechargePoints() : 
                            (vipPackage.getTotalQuota() != null ? 
                                // 如果有现有套餐，计算当前充值的积分差额
                                (existingPackage != null && existingPackage.getTotalQuota() != null ? 
                                    vipPackage.getTotalQuota() - existingPackage.getTotalQuota() : 
                                    vipPackage.getTotalQuota()) : 
                                0),
                            vipPackage.getExtensionDays() != null ? vipPackage.getExtensionDays() : 30
                        );
                        log.info("未找到packageDetails字段，使用构建的值: {}", packageDetails);
                    }
                } else {
                    // 使用默认方式构建packageDetails
                    packageDetails = String.format(
                        "{\"price\": %d, \"points\": %d, \"duration\": \"%d天\"}", 
                        packagePrice, 
                        // 优先使用单次充值积分，确保显示的是本次充值的积分值
                        vipPackage.getSingleRechargePoints() != null ? vipPackage.getSingleRechargePoints() : 
                        (vipPackage.getTotalQuota() != null ? 
                            // 如果有现有套餐，计算当前充值的积分差额
                            (existingPackage != null && existingPackage.getTotalQuota() != null ? 
                                vipPackage.getTotalQuota() - existingPackage.getTotalQuota() : 
                                vipPackage.getTotalQuota()) : 
                            0),
                        vipPackage.getExtensionDays() != null ? vipPackage.getExtensionDays() : 30
                    );
                    log.info("recordDetails不是Map或为空，使用默认构建的packageDetails: {}", packageDetails);
                }
                
                // 记录详细的日志，便于后续排查
                if (vipPackage.getSingleRechargePoints() != null) {
                    log.info("使用前端传递的单次充值积分: {}", vipPackage.getSingleRechargePoints());
                } else {
                    log.info("前端未传递单次充值积分，使用总积分: {}", 
                        (vipPackage.getTotalQuota() != null ? vipPackage.getTotalQuota() : 0));
                }
                
                rechargeRecord.setPackageDetails(packageDetails);
                
                // 设置转账时间
                rechargeRecord.setTransferTime(new Date());
                
                // 设置到期时间
                rechargeRecord.setUpdateTime(vipPackage.getEndTime());
                
                // 未删除
                rechargeRecord.setIsDeleted(0);
                
                // 保存充值记录
                rechargeRecordService.insertRechargeRecord(rechargeRecord);
                log.info("创建充值记录成功，记录ID={}", rechargeRecord.getId());
            } catch (Exception e) {
                log.error("创建充值记录失败", e);
                // 不影响充值结果
            }
        }
        
        return result;
    }

    /**
     * 获取用户最新的VIP套餐信息
     * @param userId 用户ID
     * @return 套餐信息
     */
    @Override
    public VipPackage getUserLatestPackage(Long userId) {
        if (userId == null) {
            return null;
        }
        
        // 创建查询条件
        VipPackage queryParams = new VipPackage();
        queryParams.setUserId(userId);
        queryParams.setIsDeleted(0); // 使用整数0表示未删除
        
        // 查询该用户的套餐
        List<VipPackage> userPackages = vipPackageMapper.selectVipPackageList(queryParams);
        
        if (userPackages == null || userPackages.isEmpty()) {
            return null;
        }
        
        // 如果有多条记录，选择创建时间最新的一条
        if (userPackages.size() > 1) {
            userPackages.sort((a, b) -> {
                if (a.getCreateTime() == null) return 1;
                if (b.getCreateTime() == null) return -1;
                return b.getCreateTime().compareTo(a.getCreateTime());
            });
        }
        
        return userPackages.get(0);
    }

    /**
     * 根据用户ID查询VIP套餐
     *
     * @param userId 用户ID
     * @return VIP套餐
     */
    public VipPackage selectVipPackageByUserId(Long userId) {
        if (userId == null) {
            return null;
        }
        
        VipPackage query = new VipPackage();
        query.setUserId(userId);
        query.setIsDeleted(0); // 只查询未删除的记录
        
        List<VipPackage> packages = vipPackageMapper.selectVipPackageList(query);
        if (packages != null && !packages.isEmpty()) {
            // 返回第一个匹配的套餐
            return packages.get(0);
        }
        
        return null;
    }

    /**
     * 获取用户充值历史记录
     * @param userId 用户ID
     * @return 充值记录列表
     */
    private List<RechargeRecord> getUserRechargeHistory(Long userId) {
        if (userId == null) {
            return java.util.Collections.emptyList();
        }
        
        // 创建查询对象
        RechargeRecord query = new RechargeRecord();
        query.setUserId(userId);
        query.setIsDeleted(0); // 未删除的记录
        
        // 查询该用户的充值记录
        return rechargeRecordService.selectRechargeRecordList(query);
    }
}